import { drawerAop } from "../drawer-aop";
import { BaseDrawInfo, BaseLineInfo } from "../base";
import _ from "lodash";

export interface RectInfo {
  x: number;
  y: number;
  w: number;
  h: number;
  cornerRadius?: number;
}
export interface RectDrawInfo extends BaseDrawInfo, RectInfo, BaseLineInfo {}

export class RectHelper {
  // 饿汉模式创建辅助类
  static _helper: RectHelper = new RectHelper();
  static getInstance() {
    return this._helper;
  }

  protected constructor() {}

  @drawerAop({ dealStrokeFill: true })
  draw(ctx: CanvasRenderingContext2D, drawInfo: RectDrawInfo) {
    const { x, y, w, h, cornerRadius } = drawInfo;
    if (cornerRadius) {
      let r = cornerRadius;
      if (2 * r > Math.min(w, h)) r = Math.min(w, h) / 2;
      ctx.moveTo(x + r, y);
      ctx.lineTo(x + w - r, y);
      // 第一个 x/y 是两条直线的交叉点，第二个 x/y 是圆弧终点
      ctx.arcTo(x + w, y, x + w, y + r, r);
      ctx.lineTo(x + w, y + h - r);
      ctx.arcTo(x + w, y + h, x + w - r, y + h, r);
      ctx.lineTo(x + r, y + h);
      ctx.arcTo(x, y + h, x, y + h - r, r);
      ctx.lineTo(x, y + r);
      ctx.arcTo(x, y, x + r, y, r);
    } else {
      ctx.rect(x, y, w, h);
    }
  }

  clear(ctx: CanvasRenderingContext2D, rectInfo?: RectInfo) {
    // let { x, y, w, h } = rectInfo;
    let x = rectInfo?.x ?? 0;
    let y = rectInfo?.y ?? 0;
    let w = rectInfo?.w ?? ctx.canvas.width;
    let h = rectInfo?.h ?? ctx.canvas.height;
    ctx.clearRect(x, y, w, h);
  }
}

export const rect = RectHelper.getInstance();
